package com.xuecheng.manager_cms_client.service;

import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.xuecheng.framework.domain.cms.CmsPage;
import com.xuecheng.framework.domain.cms.CmsSite;
import com.xuecheng.manager_cms_client.dao.CmsPageRepository;
import com.xuecheng.manager_cms_client.dao.CmsSiteRepository;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.Optional;

@Service
public class PageService {
private  static  final Logger LOGGER = LoggerFactory.getLogger(PageService.class);

    @Autowired
    private CmsPageRepository cmsPageRepository;

    @Autowired
    private GridFSBucket gridFSBucket;

    @Autowired
    private GridFsTemplate gridFsTemplate;

    @Autowired
    private CmsSiteRepository cmsSiteRepository;


    //保存页面到服务器物理路径
    public  void savePageToServerPath(String pageId){

        //根据pageId得到CmsPage
        CmsPage cmsPage = this.findCmsPageById(pageId);

        String htmlFileId = cmsPage.getHtmlFileId();

        //文件内容
        InputStream inputStream = this.getFileById(htmlFileId);
        if(inputStream == null){
            LOGGER.error("exec getFileById InputStream is null ,htmlFileId:{}",htmlFileId);
            return ;
        }

        //站点信息
        CmsSite cmsSite = this.findCmsSiteById(cmsPage.getSiteId());
        //站点物理路径
        String sitePath =cmsSite.getSitePhysicalPath();
        //得到页面的物理路径
        String pagePath = cmsPage.getPagePhysicalPath();
        //页面名称
        String pageName = cmsPage.getPageName();
       //站点页面的物理路径
        String sitePagePath = sitePath+pagePath+pageName;
        //保存页面到站点的物理路径
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(new File(sitePagePath));
            IOUtils.copy(inputStream,fileOutputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
                try {
                    if(inputStream != null) {
                        inputStream.close();
                    }
                    if(fileOutputStream != null){
                        fileOutputStream.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }


        }


    }

    public CmsPage findCmsPageById(String pageId) {
        Optional<CmsPage> byId = cmsPageRepository.findById(pageId);
        if(byId.isPresent()){
            CmsPage cmsPage = byId.get();
            return cmsPage;
        }
        return null;
    }

    //通过文件ID找到文件内容
    @SuppressWarnings("all")
    private InputStream getFileById(String fileId){
        GridFSFile id = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(fileId)));
        GridFSDownloadStream downloadStream = gridFSBucket.openDownloadStream(id.getObjectId());
        GridFsResource fsResource = new GridFsResource(id,downloadStream);
        try {
            return fsResource.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    //根据站点ID得到站点信息
    public CmsSite findCmsSiteById(String siteId){
        Optional<CmsSite> byId = cmsSiteRepository.findById(siteId);
        if(byId.isPresent()){
            CmsSite cmsSite = byId.get();
            return cmsSite;
        }
        return null;
    }
}
